/****************************************************************************
Copyright (c) 2015 Chukong Technologies Inc.
 
http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.javascript;

import android.Manifest;
import android.app.AlertDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.cocos2dx.javascript.Camera.CameraMgr;
import org.cocos2dx.javascript.Mob.PhoneLoginMgr;
import org.cocos2dx.javascript.Voice.AudioManager;
import org.cocos2dx.javascript.Voice.MediaManager;
import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView;
import org.cocos2dx.lib.Cocos2dxHelper;
import org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class AppActivity extends Cocos2dxActivity {


    public static String queryStr = "";
    private Handler mJniHandler;  //jnihelper 的handler
    private static AppActivity g_instance;
    public IWXAPI api;
    private Handler mPhoneHandler;
    public static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 0;
    public static final int MY_PERMISSIONS_REQUEST_RECORD_AUDIO = 1;
    public static final int MY_PERMISSIONS_REQUEST_REQUESTCODE = 2;
    
    public static final int MY_PERMISSIONS_REQUEST_GET_UNKNOWN_APP_SOURCES = 3;

    public static final int MY_PERMISSIONS_REQUEST_PHONE = 1024;

    //拍照相关
    public static final int PHOTO_GALLERY = 2000;
    public static final int PHOTO_CAMERA = 2001;
    public static final int CAMERA_PERMISSION_CODE = 2002;
    public static final int PHOTO_CLIP = 2003;



    ArrayList<String> mRequestPermissions = new  ArrayList<String>();

    public static final String TAG = "AppActivity";
    private int defaultUi = 0;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    /**
     * 钉钉
     * */
   // private IDDShareApi iddShareApi ;

    /**
     * apk文件路径
     * */
    private String apkFilePath = "";
    /**
     * apk名字
     * */
    private String apkName = "";
    public static AppActivity getInstance(){
        return g_instance;
    }

    private long starttime;


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //Log.e("onKeyDown>>>>>>>>", "onKeyDown");
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            //        //一定要在GL线程中执行
            //Log.e("onKeyDown>>>>>>>>", "onKeyDown");
            Cocos2dxHelper.runOnGLThread(new Runnable() {
                @Override
                public void run() {
                    Cocos2dxJavascriptJavaBridge.evalString("app.Client.OnNativeNotify('KeyCodeBack','{}')");
                }
            });
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    // 提供一个方法来调用父类的 onKeyDown
    public boolean callSuperOnKeyDown(int keyCode) {
        this.onBackPressed();
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //SDKWrapper.getInstance().init(this);
        //applicationContext = this;
        api = WXAPIFactory.createWXAPI(this, Contants.WX_APP_ID, true);
        api.registerApp(Contants.WX_APP_ID);

        //保持亮屏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        g_instance = this;

        Intent i_getvalue = getIntent();
        String action = i_getvalue.getAction();
        if (Intent.ACTION_VIEW.equals(action)) {
            Uri uri = i_getvalue.getData();
            if (uri != null) {
//                String host = uri.getHost();
//                String dataString = i_getvalue.getDataString();
//                String id = uri.getQueryParameter("d");
//                String path = uri.getPath();
//                String path1 = uri.getEncodedPath();
                AppActivity.queryStr = uri.getQuery();
            }
        }
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();

        initHelper();

    }

    public boolean IsOpenPrivacyDialog(){
        SharedPreferences sharedPreferences = getSharedPreferences("share", MODE_PRIVATE);
        //默认false
        boolean isFirstRun = sharedPreferences.getBoolean("isFirstRun", true);
        if (isFirstRun){
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean("isFirstRun", false);
            editor.commit();
        }

        String []permissions = {
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
        };

        for(int i = 0; i < permissions.length; i++){
            if (ContextCompat.checkSelfPermission(AppActivity.getInstance(), permissions[i]) != PackageManager.PERMISSION_GRANTED){
               return true;
            }
        }

        //首次打开或者权限不足则弹隐私窗口
        return isFirstRun;
    }
    

    public void RequestPrivacyPermission(){
        String []permissions = {
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
        };

        mRequestPermissions.clear();
        for(int i = 0; i < permissions.length; i++){
            if (ContextCompat.checkSelfPermission(AppActivity.getInstance(), permissions[i]) != PackageManager.PERMISSION_GRANTED){
                mRequestPermissions.add(permissions[i]);
            }
        }

        if (mRequestPermissions.size() > 0){
            //用作区分加了1000
            ActivityCompat.requestPermissions(AppActivity.getInstance(), (String[]) mRequestPermissions.toArray(new String[mRequestPermissions.size()]), mRequestPermissions.size() + 1000);
        }
        else{
            //Toast.makeText(this, "不需要申请权限", Toast.LENGTH_SHORT).show();
            initPhoneHandler();
        }
    }

    public void jumpToAppPrivacySetting(Context content){
        Intent mIntent = new Intent();
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9){
            mIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            mIntent.setData(Uri.fromParts("package", content.getPackageName(), null));
        }
        else{
            mIntent.setAction(Intent.ACTION_VIEW);
            mIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
            mIntent.putExtra("com.android.settings.ApplicationPkgName", content.getPackageName());
        }
        content.startActivity(mIntent);

    }

    public void requestPermission() throws JSONException {
        ArrayList<String> list = this.getLackPermissions();
        int size=list.size();
        if (size > 0) {
            ActivityCompat.requestPermissions(this, (String[]) list.toArray(new String[size]), 1024);
        }
        else{
            PhoneLoginMgr.getInstance().requestPermissionCallback(true);
        }
    }

    private ArrayList<String> getLackPermissions(){
        ArrayList<String> list = new ArrayList<>();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                PackageManager pm = getPackageManager();
                PackageInfo pi = pm.getPackageInfo(getPackageName(), PackageManager.GET_PERMISSIONS);
                for (String p : pi.requestedPermissions) {
                    if (checkSelfPermission(p) != PackageManager.PERMISSION_GRANTED) {
                        list.add(p);
                    }
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }

        if (!list.contains(Manifest.permission.INTERNET) && ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET)
                != PackageManager.PERMISSION_GRANTED){
            list.add(Manifest.permission.INTERNET);
        }

        if (!list.contains(Manifest.permission.CALL_PHONE) && ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
                != PackageManager.PERMISSION_GRANTED){
            list.add(Manifest.permission.CALL_PHONE);
        }

        if (!list.contains(Manifest.permission.INTERNET) && ContextCompat.checkSelfPermission(this, Manifest.permission.MODIFY_AUDIO_SETTINGS)
                != PackageManager.PERMISSION_GRANTED){
            list.add(Manifest.permission.MODIFY_AUDIO_SETTINGS);
        }

        if (!list.contains(Manifest.permission.WRITE_EXTERNAL_STORAGE) && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){
            list.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }

        if (!list.contains(Manifest.permission.ACCESS_WIFI_STATE) &&  ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_WIFI_STATE)
                != PackageManager.PERMISSION_GRANTED){
            list.add(Manifest.permission.ACCESS_WIFI_STATE);
        }

        if (!list.contains(Manifest.permission.READ_PHONE_STATE) && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED){
            list.add(Manifest.permission.READ_PHONE_STATE);
        }

        if (!list.contains(Manifest.permission.ACCESS_NETWORK_STATE) && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE)
                != PackageManager.PERMISSION_GRANTED){
            list.add(Manifest.permission.ACCESS_NETWORK_STATE);
        }

        return list;
    }

    public Handler getPhoneHandler(){
        return this.mPhoneHandler;
    }

    public void initPhoneHandler(){
        PhoneLoginMgr.getInstance().init(this);
        mPhoneHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg){
                if(msg.what == Contants.MSG_QUICK_GET_PHONE
                || msg.what == Contants.MSG_PHONE_VERIFY_LOGIN)
                {
                    PhoneLoginMgr.getInstance().handleMessage(mPhoneHandler, msg);
                }
                return  false;
            }
        });
    }
    // 初始化jnihelper
    public void initHelper() {
        mJniHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg){
                if(msg.what == Contants.MSG_OpenApk)
                {
                    String filePath = msg.getData().getString("filePath");
                    String apkName = msg.getData().getString("apkName");
                    try {
                        downLoad( filePath, apkName);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();

                        Toast.makeText(getContext(), "安装失败!请重新安装!", Toast.LENGTH_LONG).show();
                    }
                }else if(msg.what == Contants.MSG_COPYTEXT){
                    String message = msg.getData().getString("msg");
                    ClipboardManager clipBoard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    // 将文本内容放到系统剪贴板里。
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                        clipBoard.setText(message);
                    }

                    try {

                        JSONObject mJsonobjData = new JSONObject();
                        mJsonobjData.put("code", 0);
                        mJsonobjData.put("msg", message);
                        NativeMgr.OnCallBackToJs("copyText", mJsonobjData.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }else if(msg.what == Contants.MSG_YAOQING){
                    Log.e(TAG, "MSG_YAOQING");
                }
                return  false;
            }
        });
        org.cocos2dx.javascript.NativeMgr.mJniHandler = mJniHandler;
    }

    public void downLoad(String filePath, String apkName) throws InterruptedException
    {
        //方法2，直接更改文件权限
        Process p;
        int status = -1;
        try {
            p = Runtime.getRuntime().exec("chmod 777 " + filePath+ apkName);
            status = p.waitFor();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (status == 0) {
            //Log.e("chmod", "succeed");
            //Toast.makeText(this, "chmod succeed", Toast.LENGTH_LONG).show();
        } else {
            //Log.e("chmod", "failed");
            //Toast.makeText(this, "chmod failed", Toast.LENGTH_LONG).show();
        }

        File file = new File(filePath,apkName);
        Log.e("downLoad", "123456 file.exites()="+file.exists());
        if(file.exists())
        {
            Log.e("downLoad", "file exist");
            this.apkFilePath = filePath;
            this.apkName  = apkName;
            checkOreo();
        }
    }

    public String GetQueryStr() {
        return AppActivity.queryStr;
    }

    @Override
    public Cocos2dxGLSurfaceView onCreateView() {
        Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
        // TestCpp should create stencil buffer
        glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);

        //SDKWrapper.getInstance().setGLSurfaceView(glSurfaceView);

        return glSurfaceView;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //SDKWrapper.getInstance().onResume();
        MediaManager.getInstance().resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //SDKWrapper.getInstance().onPause();
        MediaManager.getInstance().pause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //SDKWrapper.getInstance().onDestroy();
        //Location.getInstance().onDestroy();
        AudioManager.getInstance().release();
        MediaManager.getInstance().release();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //SDKWrapper.getInstance().onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_GET_UNKNOWN_APP_SOURCES:
                checkOreo();
                break;
            case PHOTO_GALLERY:
            case PHOTO_CAMERA:
            case PHOTO_CLIP:
            
            case CAMERA_PERMISSION_CODE:
                CameraMgr.getInstance().onActivityResult(requestCode, resultCode, data);
        }
            
    }
    

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //SDKWrapper.getInstance().onNewIntent(intent);

        setIntent(intent);
        handlerIntent(intent);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        //SDKWrapper.getInstance().onRestart();
    }

    @Override
    protected void onStop() {
        super.onStop();// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        //SDKWrapper.getInstance().onStop();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.disconnect();
    }

    @Override
    public void onBackPressed() {
        //SDKWrapper.getInstance().onBackPressed();
        super.onBackPressed();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        //SDKWrapper.getInstance().onConfigurationChanged(newConfig);
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        //SDKWrapper.getInstance().onRestoreInstanceState(savedInstanceState);
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //SDKWrapper.getInstance().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onStart() {
        //SDKWrapper.getInstance().onStart();
        super.onStart();// ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("App Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    //屏幕选装的
    public  void changeOrientationH(boolean val){
        if (val){
            Log.d("changeOrientationH","H");
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
        }else{
            Log.d("changeOrientationH","V");
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode){
            case MY_PERMISSIONS_REQUEST_READ_PHONE_STATE:
                if (grantResults.length > 0 &&  grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                }
                else {// Permission Denied
                    Toast.makeText(this, "请开启应用获取手机状态权限", Toast.LENGTH_LONG).show();
                }
                break;
            case  MY_PERMISSIONS_REQUEST_RECORD_AUDIO:
                if (grantResults.length > 0 &&  grantResults[0] == PackageManager.PERMISSION_GRANTED){
                }
                else{// Permission Denie
                    Toast.makeText(this, "请开启应用录音权限", Toast.LENGTH_LONG).show();
                }
                break;
            case  MY_PERMISSIONS_REQUEST_REQUESTCODE:
                if (grantResults.length > 0 &&  grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    Log.e(TAG, "权限_REQUESTCODE申请成功");
                }
                else{// Permission Denied
                    Log.e(TAG, "权限权限_REQUESTCODE申请成功申请失败");
                    Toast.makeText(this, "请开启应用定位权限", Toast.LENGTH_LONG).show();
                }
                break;
            case MY_PERMISSIONS_REQUEST_GET_UNKNOWN_APP_SOURCES:
                if (grantResults.length > 0 &&  grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    checkOreo();
                }
                else{// Permission Denied
                    Log.e(TAG, "权限权限install apk 申请成功申请失败");
                    Toast.makeText(this, "请开启应用定位权限", Toast.LENGTH_LONG).show();
                }
                break;
            case MY_PERMISSIONS_REQUEST_PHONE:
                try {
                    PhoneLoginMgr.getInstance().requestPermissionCallback(true);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                
                /*if (grantResults.length > 0 &&  grantResults[0] == PackageManager.PERMISSION_GRANTED){

                    
                }
                else{// Permission Denied
                    Log.e(TAG, "权限权限手机号码 申请成功申请失败");
                    Toast.makeText(this, "请开启申请手机号码权限", Toast.LENGTH_LONG).show();
                }*/
                break;

            default:
                if (requestCode > 1000){
                    boolean isAllAccept = true;
                    for(int i = 0; i < grantResults.length; i++){
                        if (grantResults[i] == PackageManager.PERMISSION_DENIED){
                            isAllAccept  = false;
                        }
                    }

                    if (!isAllAccept){
                        //当拒绝了授权后，为提升用户体验，可以以弹窗的方式引导用户到设置中去进行设置
                        new AlertDialog.Builder(AppActivity.getInstance())
                                .setMessage("开启需要的权限才能使用本应用")
                                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //引导用户到设置中去进行设置
                                        Intent intent = new Intent();
                                        intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                                        intent.setData(Uri.fromParts("package", getPackageName(), null));
                                        startActivity(intent);

                                        finish();
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        finish();
                                    }
                                })
                                .create()
                                .show();
                    }
                    else{

                    }
                    initPhoneHandler();
                }
                break;
        }

    }

    private void handlerIntent(Intent intent) {
        if(null == intent || null == intent.getDataString() || intent.getDataString().isEmpty()) return;
        Toast.makeText(this, "handlerIntent intent="+intent.getDataString(), Toast.LENGTH_LONG).show();
        Log.e(TAG, "handlerIntent intent="+intent.getDataString());
        /**
         *  接收闲聊传入roomId, roomToken
         */
        String roomId = intent.getStringExtra("roomId");
        String openId = intent.getStringExtra("openId");
        String roomToken = intent.getStringExtra("roomToken");
        Log.e(TAG, "roomID="+roomId+",roomToken="+roomToken+", openID="+openId);
        if ( null == roomId || roomId.isEmpty()  || null == openId || openId.isEmpty() || null == roomToken || roomToken.isEmpty())
            return;
        try {
            JSONObject mJsonobjData = new JSONObject();
            mJsonobjData.put("roomID", roomId);
            mJsonobjData.put("roomToken", roomToken);
            mJsonobjData.put("openID", openId);
            NativeMgr.OnCallBackToJs("XLShareYaoQing", mJsonobjData.toString());
        } catch (JSONException e) {
            Log.e(TAG, e.toString());
        }
    }

    /**
     * 检测版本8.0
     */
    public void checkOreo() {

        Log.e(TAG, "checkOreo  000000");
        //判断是否可以直接安装
        if (android.os.Build.VERSION.SDK_INT >= 26) {
                installApk();

        }else {
            //安装apk
            installApk();
        }
    }

    public  void installApk(){
        File file = new File(this.apkFilePath, this.apkName);
        Log.e("downLoad", "123456");
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Log.w(TAG, "版本大于 N ，开始使用 fileProvider 进行安装");

            /*  StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy( builder.build() );
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");*/

            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION );
            Uri apkUri = FileProvider.getUriForFile(getContext(), "com.pelbs.book99998.fileProvider", file);//在AndroidManifest中的android:authorities值
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");


        } else {
            Log.w(TAG, "正常进行安装");
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }

//                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }




   
}
